import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { In, Repository } from 'typeorm'
import { CreateMenuDto } from './dto/create-menu.dto'
import { UpdateMenuDto } from './dto/update-menu.dto'
import { MenuEntity } from './entities/menu.entity'

@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(MenuEntity)
    private readonly menuRepository: Repository<MenuEntity>,
  ) {}

  // 新增
  async create(dto: CreateMenuDto) {
    const result = await this.menuRepository.create(dto)
    await this.menuRepository.save(result)

    return result
  }

  // 列表
  async findAll() {
    return await this.menuRepository.find({
      order: {
        order: 'ASC',
      },
    })
  }

  // 通过Id数组查询
  async findAllByIds(ids: number[]) {
    return this.menuRepository.find({
      where: {
        id: In(ids),
      },
    })
  }

  // 详情
  findOne(id) {
    return this.menuRepository.findOne({ where: { id } })
  }

  // 修改
  async update(id: number, dto: UpdateMenuDto) {
    const old = await this.findOne(id)
    const vo = await this.menuRepository.merge(old, dto)

    return this.menuRepository.save(vo)
  }

  // 删除
  async remove(id) {
    const result = await this.menuRepository.delete(id)
    Logger.log(`删除返回数据：${JSON.stringify(result)}`)

    return result.affected || new HttpException('无法删除，请稍候在试', HttpStatus.BAD_REQUEST)
  }
}
